

package com.zdkj.subway.stm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.entity.SwStApplyNetworkCheckPassengerAffairs;
import com.zdkj.subway.stm.enums.CycleEnum;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.service.SwStApplyNetworkCheckPassengerAffairsService;
import com.zdkj.subway.stm.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;


/**
 * 申请线网协查乘客事务
 *
 * @author chenbo
 * @date 2020-02-06 19:49:06
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swstapplynetworkcheckpassengeraffairs")
@Api(value = "swstapplynetworkcheckpassengeraffairs", tags = "申请线网协查乘客事务管理")
public class SwStApplyNetworkCheckPassengerAffairsController {

    private final SwStApplyNetworkCheckPassengerAffairsService swStApplyNetworkCheckPassengerAffairsService;
    private final SystemUserService systemUserService;

    /**
     * 分页查询
     *
     * @param page                                  分页对象
     * @param swStApplyNetworkCheckPassengerAffairs 申请线网协查乘客事务
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getPage(Page page, SwStApplyNetworkCheckPassengerAffairs swStApplyNetworkCheckPassengerAffairs, String[] dates) {
        String startDate = null;
        String endDate = null;
        boolean dateFlag = false;
        if (dates != null) {
            dateFlag = true;
            String s = dates[0];
            try {
                String decode = URLDecoder.decode(s, "utf-8");
                String[] split = decode.split("&");
                startDate = split[0].substring(6);
                endDate = split[1].substring(6);
                swStApplyNetworkCheckPassengerAffairs.setTransactionTime(null);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        String stationCode = SecurityUtils.getUser().getStationCode();
        if (SecurityUtils.getUser().getBelongToLine()) {
            return R.ok(swStApplyNetworkCheckPassengerAffairsService
                    .page(page, Wrappers.query(swStApplyNetworkCheckPassengerAffairs).lambda()
                            .between(dateFlag, SwStApplyNetworkCheckPassengerAffairs::getTransactionTime, startDate, endDate)
                            .like(swStApplyNetworkCheckPassengerAffairs.getCardNumber()==null?false:true,
                                    SwStApplyNetworkCheckPassengerAffairs::getCardNumber,
                                    swStApplyNetworkCheckPassengerAffairs.getCardNumber())
                            .and(i -> i.eq(SwStApplyNetworkCheckPassengerAffairs::getApplyStatus,
                                    CycleEnum.PASSENGERS_STATUS_IS.getCode())
                                    .or().eq(SwStApplyNetworkCheckPassengerAffairs::getApplyStatus,
                                            CycleEnum.PASSENGERS_STATUS_COMPLETE.getCode()))
                    ));
        } else {
            return R.ok(swStApplyNetworkCheckPassengerAffairsService.page(page, Wrappers.query(swStApplyNetworkCheckPassengerAffairs)
                    .lambda()
                    .between(dateFlag, SwStApplyNetworkCheckPassengerAffairs::getTransactionTime, startDate, endDate)
                    .eq(SwStApplyNetworkCheckPassengerAffairs::getStationCode, stationCode)
                    .like(swStApplyNetworkCheckPassengerAffairs.getCardNumber()==null?false:true,
                            SwStApplyNetworkCheckPassengerAffairs::getCardNumber,
                            swStApplyNetworkCheckPassengerAffairs.getCardNumber())));
        }
    }

    /**
     * 通过id查询申请线网协查乘客事务
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.getById(id));
    }

    /**
     * 新增申请线网协查乘客事务
     *
     * @param swStApplyNetworkCheckPassengerAffairs 申请线网协查乘客事务
     * @return R
     */
    @ApiOperation(value = "新增申请线网协查乘客事务", notes = "新增申请线网协查乘客事务")
    @SysLog("新增申请线网协查乘客事务")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_add')")
    public R save(@RequestBody SwStApplyNetworkCheckPassengerAffairs swStApplyNetworkCheckPassengerAffairs) {
        SwStApplyNetworkCheckPassengerAffairs defaultObj = ObjectValueUtils
                .getDefaultObj(SwStApplyNetworkCheckPassengerAffairs.class);
        BeanUtil.copyProperties(swStApplyNetworkCheckPassengerAffairs, defaultObj,
                CopyOptions.create().setIgnoreProperties(BeanPropertyUtils.
                        getNullAndEmptyPropertyNames(swStApplyNetworkCheckPassengerAffairs)));
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.save(defaultObj));
    }

    /**
     * 批量提交线网协查乘客事务
     *
     * @param inList 线网协查乘客事务表
     * @return R
     */
    @ApiOperation(value = "批量提交线网协查乘客事务", notes = "批量提交线网协查乘客事务")
    @SysLog("批量提交线网协查乘客事务")
    @PutMapping("/submitBatch")
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_submitBatch')")
    public R submitBatch(@RequestBody List<SwStApplyNetworkCheckPassengerAffairs> inList) {
        for (SwStApplyNetworkCheckPassengerAffairs in : inList) {
            in.setApplyStatus(CycleEnum.PASSENGERS_STATUS_IS.getCode());
        }
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.updateBatchById(inList));
    }

    /**
     * 批量下发线网协查乘客事务
     *
     * @param inList 线网协查乘客事务表
     * @return R
     */
    @ApiOperation(value = "批量下发线网协查乘客事务", notes = "批量下发线网协查乘客事务")
    @SysLog("批量下发线网协查乘客事务")
    @PutMapping("/sendBatch")
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_sendBatch')")
    public R sendBatch(@RequestBody List<SwStApplyNetworkCheckPassengerAffairs> inList) {
        for (SwStApplyNetworkCheckPassengerAffairs in : inList) {
            in.setApplyStatus(CycleEnum.PASSENGERS_STATUS_COMPLETE.getCode());
        }
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.updateBatchById(inList));
    }

    /**
     * 修改申请线网协查乘客事务
     *
     * @param swStApplyNetworkCheckPassengerAffairs 申请线网协查乘客事务
     * @return R
     */
    @ApiOperation(value = "修改申请线网协查乘客事务", notes = "修改申请线网协查乘客事务")
    @SysLog("修改申请线网协查乘客事务")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_edit')")
    public R updateById(@RequestBody SwStApplyNetworkCheckPassengerAffairs swStApplyNetworkCheckPassengerAffairs) {
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.updateById(swStApplyNetworkCheckPassengerAffairs));
    }

    /**
     * 线网审批乘客事务
     *
     * @param swStApplyNetworkCheckPassengerAffairs 线网审批乘客事务
     * @return R
     */
    @ApiOperation(value = "线网审批乘客事务", notes = "线网审批乘客事务")
    @SysLog("线网审批乘客事务")
    @PutMapping("approval")
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_approval')")
    public R approval(@RequestBody SwStApplyNetworkCheckPassengerAffairs swStApplyNetworkCheckPassengerAffairs) {
        if (swStApplyNetworkCheckPassengerAffairs == null) {
            return R.ok();
        }
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.updateById(swStApplyNetworkCheckPassengerAffairs));
    }

    /**
     * 通过id删除申请线网协查乘客事务
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除申请线网协查乘客事务", notes = "通过id删除申请线网协查乘客事务")
    @SysLog("通过id删除申请线网协查乘客事务")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStApplyNetworkCheckPassengerAffairsService.removeById(id));
    }

    @GetMapping("/export")
    @SysLog("导出线网协查乘客事务信息")
    @PreAuthorize("@pms.hasPermission('stm_swstapplynetworkcheckpassengeraffairs_export')")
    public void exportExcel(Page page, SwStApplyNetworkCheckPassengerAffairs swStApplyNetworkCheckPassengerAffairs, String[] dates,
                            HttpServletResponse response) throws IOException {
        String startDate = null;
        String endDate = null;
        boolean dateFlag = false;
        if (dates != null) {
            dateFlag = true;
            String s = dates[0];
            try {
                String decode = URLDecoder.decode(s, "utf-8");
                String[] split = decode.split("&");
                startDate = split[0].substring(6);
                endDate = split[1].substring(6);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String stationCode = SecurityUtils.getUser().getStationCode();
        List<SwStApplyNetworkCheckPassengerAffairs> swStApplyNetworkCheckPassengerAffairsList;

        if (SecurityUtils.getUser().getBelongToLine()) {
            swStApplyNetworkCheckPassengerAffairsList = swStApplyNetworkCheckPassengerAffairsService
                    .pageMapper(page, Wrappers.query(swStApplyNetworkCheckPassengerAffairs)
                            .allEq(SelMapUtils.getSwStApplyNetworkCheckPassengerAffairsMap(swStApplyNetworkCheckPassengerAffairs), false)
                            .lambda()
                            .between(dateFlag, SwStApplyNetworkCheckPassengerAffairs::getTransactionTime, startDate, endDate)
                            .like(swStApplyNetworkCheckPassengerAffairs.getCardNumber()==null?false:true,
                                    SwStApplyNetworkCheckPassengerAffairs::getCardNumber,
                                    swStApplyNetworkCheckPassengerAffairs.getCardNumber())
                            .and(i -> i.eq(SwStApplyNetworkCheckPassengerAffairs::getApplyStatus,
                                    CycleEnum.PASSENGERS_STATUS_IS.getCode())
                                    .or().eq(SwStApplyNetworkCheckPassengerAffairs::getApplyStatus,
                                            CycleEnum.PASSENGERS_STATUS_COMPLETE.getCode()))
                    ).getRecords();
        } else {
            swStApplyNetworkCheckPassengerAffairsList = swStApplyNetworkCheckPassengerAffairsService.page(page, Wrappers.query(swStApplyNetworkCheckPassengerAffairs)
                    .lambda()
                    .between(dateFlag, SwStApplyNetworkCheckPassengerAffairs::getTransactionTime, startDate, endDate)
                    .eq(SwStApplyNetworkCheckPassengerAffairs::getStationCode, stationCode)
                    .like(swStApplyNetworkCheckPassengerAffairs.getCardNumber()==null?false:true,
                            SwStApplyNetworkCheckPassengerAffairs::getCardNumber,
                            swStApplyNetworkCheckPassengerAffairs.getCardNumber())).getRecords();
        }
        // 写法1
        String fileName = URLEncoder.encode("线网协查乘客事务", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStApplyNetworkCheckPassengerAffairs.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("乘客事务信息").doWrite(swStApplyNetworkCheckPassengerAffairsList);
    }
}
